package com.group01.community.controller;


import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.group01.community.entity.ZyOwner;
import com.group01.community.entity.vo.ZyOwnerVO;
import com.group01.community.service.ZyOwnerService;
import com.group01.community.utils.ResponseResult;
import com.group01.community.utils.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;


/**
 * <p>
 * 业主  前端控制器
 * </p>
 *
 * @author xuxu
 * @since 2022-07-04
 */
@Api(tags = "业主绑定信息")
@RestController
@RequestMapping("zyOwner")
public class ZyOwnerController {
    public static final String DIR = "http://192.168.110.250/";

    @Autowired
    private ZyOwnerService zyOwnerService;

    @Autowired
    private FastFileStorageClient client;


    /**
     * 业主模糊查询 + 分页查询
     *
     * @param currents                  当前页
     * @param sizes                     每页显示的数据
     * @param zyOwnerVO                 ZyOwnerVO对象
     * @return                          业主信息的集合(分页 + 模糊查询)
     */
    @ApiOperation("业主模糊查询")
    @GetMapping("zyOwnerFuzzyQuery")
    public ResponseResult<IPage<ZyOwnerVO>> getZyOwnerFuzzyQuery(Long currents,Long sizes,ZyOwnerVO zyOwnerVO){
        IPage<ZyOwnerVO> zyOwnerIPage = zyOwnerService.sybase(currents, sizes, zyOwnerVO);
        return ResponseResult.ok(zyOwnerIPage);
    }

    /**
     * 获取所有业主信息
     * @return      业主集合
     */
    @GetMapping("list")
    public ResponseResult<List<ZyOwner>> getAllOwner(){
        return ResponseResult.ok(zyOwnerService.list());
    }

    /**
     * 通过昵称获取业主信息
     * @param ownerNickname     业主昵称
     * @return                  业主对象
     */
    @GetMapping("getOwnerByOwnerNickname/{ownerNickname}")
    public ResponseResult<ZyOwner> getOwnerByOwnerNickname(@PathVariable String ownerNickname){
        return ResponseResult.ok(zyOwnerService.getOne(new QueryWrapper<ZyOwner>().eq("owner_nickname",ownerNickname)));
    }

    /**
     * 添加业主
     * @param zyOwner   业主对象
     * @return          ok
     */
    @PostMapping("add")
    public ResponseResult<String> addOwner(ZyOwner zyOwner){
        zyOwner.setOwnerId(UUIDUtils.getId());
        String year = zyOwner.getOwnerIdCard().substring(6, 10);
        String month = zyOwner.getOwnerIdCard().substring(10, 12);
        String day = zyOwner.getOwnerIdCard().substring(12, 14);
        String birthDay = year + "-" + month + "-" + day;
        zyOwner.setOwnerBirthday(LocalDate.parse(birthDay, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        zyOwner.setOwnerType("业主");
        zyOwner.setOwnerStatus("Enable");
        zyOwner.setCreateTime(LocalDateTime.now());
        zyOwnerService.save(zyOwner);
        return ResponseResult.ok("ok");
    }

    /**
     * 业主信息更新
     * @param zyOwner  业主
     * @return
     */
    @PutMapping("update")
    public ResponseResult<String> updateOwner(@RequestBody ZyOwner zyOwner){
        zyOwner.setUpdateTime(LocalDateTime.now());
        String year = zyOwner.getOwnerIdCard().substring(6, 10);
        String month = zyOwner.getOwnerIdCard().substring(10, 12);
        String day = zyOwner.getOwnerIdCard().substring(12, 14);
        String birthDay = year + "-" + month + "-" + day;
        zyOwner.setOwnerBirthday(LocalDate.parse(birthDay, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        zyOwnerService.updateById(zyOwner);
        return ResponseResult.ok("ok");
    }

    /**
     * 上传头像
     * @param file  头像
     * @return      储存地址
     * @throws IOException
     */
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public ResponseEntity<String> upload(MultipartFile file) throws IOException {
        //获得后缀名
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        //上传
        StorePath storePath = client.uploadFile(file.getInputStream(), file.getSize(), extension, null);
        return ResponseEntity.ok(DIR + storePath.getFullPath());
    }

    /**
     * 导出
     *
     * @param currents                  当前页
     * @param sizes                     每页显示的数据
     * @param zyOwnerVO                 ZyOwnerVO对象
     * @return                          ok
     */
    @GetMapping("export")
    public void export(Long currents, Long sizes, ZyOwnerVO zyOwnerVO, HttpServletResponse response) throws IOException {

        //查询所有用户
        List<ZyOwnerVO> list = zyOwnerService.sybase(currents, sizes, zyOwnerVO).getRecords();
        list.forEach((owner) -> {
            if (owner.getOwnerGender() == "Male"){
                owner.setOwnerGender("男");
            }else{
                owner.setOwnerGender("女");
            }
        });
        //在内存操作，写到浏览器
        ExcelWriter writer= ExcelUtil.getWriter(true);

        //自定义标题别名
        writer.addHeaderAlias("ownerNickname","业主昵称");
        writer.addHeaderAlias("ownerRealName","业主姓名");
        writer.addHeaderAlias("ownerGender","业主性别");
        writer.addHeaderAlias("ownerAge","业主年龄");
        writer.addHeaderAlias("ownerPhoneNumber","手机号码");
        writer.addHeaderAlias("createTime","创建时间");
        writer.addHeaderAlias("remark","备注");

        //默认配置
        writer.write(list,true);
        // 设置只导出别名列
        writer.setOnlyAlias(true);
        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");

        //设置标题
        String fileName= URLEncoder.encode("业主信息","UTF-8");
        //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
        response.setHeader("Content-Disposition","attachment;filename="+fileName+".xlsx");
        ServletOutputStream outputStream= response.getOutputStream();

        //将Writer刷新到OutPut
        writer.flush(outputStream,true);
        outputStream.close();
        writer.close();

    }
}

